#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
智能门神系统 - 仅天气和时间，其余交给AI回复
"""

import requests
import json
import logging
import time
from datetime import datetime
import random
import urllib3
from untils.tts import play
from ai_chat import ai_reply

# 禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class SmartDoorAPI:
    def __init__(self):
        """初始化天气与时间API"""
        self.session = requests.Session()
        
        # 天气API（国内可用）
        self.apis = {
            'weather': {
                'url': 'https://api.open-meteo.com/v1/forecast',
                'params': {'latitude': 29.57, 'longitude': 106.55, 'current_weather': True}
            }
        }
        
        # 缓存
        self.cache = {}
        self.cache_timeout = 300  # 5分钟缓存
        
        # 天气备用回复
        self.fallback_responses = {
            'weather': [
                "今天天气不错，适合出门走走。",
                "记得查看天气预报，做好准备再出门。",
                "天气变化快，建议带件外套。"
            ]
        }
    
    def _make_api_request(self, api_name, custom_params=None):
        """通用API请求"""
        try:
            if api_name not in self.apis:
                return None
                
            cache_key = f"{api_name}_{str(custom_params or self.apis[api_name]['params'])}"
            if cache_key in self.cache:
                cached_data = self.cache[cache_key]
                if time.time() - cached_data['timestamp'] < self.cache_timeout:
                    return cached_data['data']
            
            params = self.apis[api_name]['params'].copy()
            if custom_params:
                params.update(custom_params)
            
            response = self.session.get(
                self.apis[api_name]['url'],
                params=params,
                timeout=8,
                verify=False
            )
            
            if response.status_code == 200:
                data = response.json()
                self.cache[cache_key] = {'data': data, 'timestamp': time.time()}
                return data
            else:
                logger.warning(f"API {api_name} 请求失败，状态码: {response.status_code}")
                return None
                
        except Exception as e:
            logger.error(f"API {api_name} 请求异常: {e}")
            return None
    
    def get_weather(self, city="重庆"):
        """获取天气信息"""
        city_coords = {
            "重庆": {"latitude": 29.57, "longitude": 106.55},
            "北京": {"latitude": 39.90, "longitude": 116.41},
            "上海": {"latitude": 31.23, "longitude": 121.47},
            "广州": {"latitude": 23.13, "longitude": 113.26},
            "深圳": {"latitude": 22.54, "longitude": 114.05},
            "杭州": {"latitude": 30.27, "longitude": 120.15}
        }
        
        if city in city_coords:
            params = city_coords[city].copy()
            params['current_weather'] = True
            data = self._make_api_request('weather', params)
            
            if data and 'current_weather' in data:
                weather = data['current_weather']
                temperature = weather['temperature']
                weather_code = weather['weathercode']
                
                weather_descriptions = {
                    0: "晴", 1: "主要晴朗", 2: "部分多云", 3: "阴天",
                    45: "雾", 48: "雾", 51: "小雨", 53: "中雨", 55: "大雨",
                    61: "小雨", 63: "中雨", 65: "大雨", 80: "阵雨", 81: "阵雨", 82: "大阵雨",
                    95: "雷暴", 96: "雷暴", 99: "强雷暴"
                }
                
                condition = weather_descriptions.get(weather_code, "未知")
                return f"{city}当前天气: {condition}, 温度: {temperature}°C"
        
        return random.choice(self.fallback_responses['weather'])
    
    def get_time(self):
        """获取当前时间"""
        now = datetime.now()
        return f"现在是{now.hour}点{now.minute}分"
    
    def process_query(self, query):
        """处理查询：只支持天气和时间"""
        query_lower = query.lower()
        
        # 天气
        if any(word in query_lower for word in ['天气', 'weather', '温度', '下雨', '下雪', "气温"]):
            cities = ["北京", "重庆", "广州", "深圳", "杭州"]
            for city in cities:
                if city in query:
                    return self.get_weather(city)
            return self.get_weather()
        
        # 时间
        elif any(word in query_lower for word in ['时间', '几点', '钟', 'time']):
            return self.get_time()
        
        # 其他 → 调用AI
        else:
            return ai_reply(query)

def reply(text):
    api = SmartDoorAPI()
    response = api.process_query(text)
    time.sleep(1)  # 避免请求过于频繁
    return response